package com.geely.club.util.httpclientpatch;

import android.util.Log;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.SyncBasicHttpContext;
import org.apache.http.util.VersionInfo;

import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.net.URLDecoder;

import util.openapiclient.ProgressCallBack;


/**
 * Created by ilioili on 2015/1/14.
 */
public class SyncHttpUtil {
    public static final String LOG_TAG = "SyncHttpUtil";

    public static HttpResponse get(String url, RequestParams params) throws IOException {
        SyncBasicHttpContext httpContext = new SyncBasicHttpContext(new BasicHttpContext());
        DefaultHttpClient httpClient = createHttpClient();
        HttpUriRequest uriRequest = new HttpGet(getUrlWithQueryString(url, params));
        uriRequest = Utils.notNull(uriRequest, "request");
        return httpClient.execute(uriRequest, httpContext);
    }

    public static HttpResponse post(String url, RequestParams params, final ProgressCallBack progressCallBack) throws IOException {
        SyncBasicHttpContext httpContext = new SyncBasicHttpContext(new BasicHttpContext());
        DefaultHttpClient httpClient = createHttpClient();
        if (null != progressCallBack) {
            progressCallBack.callBackHttpClient(httpClient);
        }
        HttpPost httpPost = new HttpPost(URI.create(url).normalize());
        HttpEntity entity = paramsToEntity(params, new ResponseHandlerInterface() {
            @Override
            public void sendResponseMessage(HttpResponse response) throws IOException {

            }

            @Override
            public void sendStartMessage() {
                if (null != progressCallBack) {
                    progressCallBack.onStart();
                }
            }

            @Override
            public void sendFinishMessage() {

            }

            @Override
            public void sendProgressMessage(int bytesWritten, int bytesTotal) {
                if (null != progressCallBack) {
                    progressCallBack.onProgress(bytesWritten, bytesTotal);
                }
            }

            @Override
            public void sendCancelMessage() {
                if (null != progressCallBack) {
                    progressCallBack.onError();
                }
            }

            @Override
            public void sendSuccessMessage(int statusCode, Header[] headers, byte[] responseBody) {
                if (null != progressCallBack) {
                    progressCallBack.onComplete();
                }
            }

            @Override
            public void sendFailureMessage(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                if (null != progressCallBack) {
                    progressCallBack.onError();
                }
            }

            @Override
            public void sendRetryMessage(int retryNo) {

            }

            @Override
            public URI getRequestURI() {
                return null;
            }

            @Override
            public Header[] getRequestHeaders() {
                return new Header[0];
            }

            @Override
            public void setRequestURI(URI requestURI) {

            }

            @Override
            public void setRequestHeaders(Header[] requestHeaders) {

            }

            @Override
            public void setUseSynchronousMode(boolean useSynchronousMode) {

            }

            @Override
            public boolean getUseSynchronousMode() {
                return false;
            }

            @Override
            public void setUsePoolThread(boolean usePoolThread) {

            }

            @Override
            public boolean getUsePoolThread() {
                return false;
            }

            @Override
            public void onPreProcessResponse(ResponseHandlerInterface instance, HttpResponse response) {

            }

            @Override
            public void onPostProcessResponse(ResponseHandlerInterface instance, HttpResponse response) {

            }
        });
        HttpEntityEnclosingRequestBase requestBase = addEntityToRequestBase(httpPost, entity);
        return httpClient.execute(requestBase, httpContext);
    }

    private static HttpEntityEnclosingRequestBase addEntityToRequestBase(HttpEntityEnclosingRequestBase requestBase, HttpEntity entity) {
        if (entity != null) {
            requestBase.setEntity(entity);
        }

        return requestBase;
    }

    private static HttpEntity paramsToEntity(RequestParams params, ResponseHandlerInterface responseHandler) {
        HttpEntity entity = null;

        try {
            if (params != null) {
                entity = params.getEntity(responseHandler);
            }
        } catch (IOException e) {
            if (responseHandler != null) {
                responseHandler.sendFailureMessage(0, null, null, e);
            } else {
                e.printStackTrace();
            }
        }

        return entity;
    }

    public static String getUrlWithQueryString(String url, RequestParams params) {
        try {
            String decodedURL = URLDecoder.decode(url, "UTF-8");
            URL _url = new URL(decodedURL);
            URI _uri = new URI(_url.getProtocol(), _url.getUserInfo(), _url.getHost(), _url.getPort(), _url.getPath(), _url.getQuery(), _url.getRef());
            url = _uri.toASCIIString();
        } catch (Exception ex) {
            Log.e(LOG_TAG, "getUrlWithQueryString encoding URL", ex);
        }

        if (params != null) {
            String paramString = params.getParamString().trim();
            if (!paramString.equals("") && !paramString.equals("?")) {
                url += url.contains("?") ? "&" : "?";
                url += paramString;
            }
        }
        return url;
    }

    private static DefaultHttpClient createHttpClient() {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        final HttpParams params = httpClient.getParams();
        ConnManagerParams.setTimeout(params, 30000);
        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        final VersionInfo vi = VersionInfo.loadVersionInfo("conf", DefaultHttpClient.class.getClassLoader());
        final String release = (vi != null) ? vi.getRelease() : VersionInfo.UNAVAILABLE;
        HttpProtocolParams.setUserAgent(params, "Gap-OpenApiClient/" + release + " (java 1.5)");
//        SchemeRegistry schReg = new SchemeRegistry();
//        schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
//        ClientConnectionManager connMgr = new ThreadSafeClientConnManager(params, schReg);
//        new AuthSchemeRegistry()
//        httpClient.setAuthSchemes(new AuthSchemeRegistry());
        return httpClient;
    }

}
